package com.bi.design.mqtt.client;

import com.alibaba.fastjson.JSONObject;
import com.bi.design.entity.DeviceData;
import com.bi.design.service.DeviceDataService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.Date;


@Slf4j
public class Callback implements MqttCallback {
    private DeviceDataService deviceDataService;

    public Callback(DeviceDataService deviceDataService) {
        this.deviceDataService = deviceDataService;
    }

    /**
     * MQTT 断开连接会执行此方法
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.info("断开了MQTT连接 ：{}", throwable.getMessage());
        log.error(throwable.getMessage(), throwable);
    }

    /**
     * publish发布成功后会执行到这里
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("发布消息成功");
    }

    /**
     * subscribe订阅后得到的消息会执行到这里
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        //  TODO    此处可以将订阅得到的消息进行业务处理、数据存储,你写代码的地方
        String deviceCode = topic.split("/")[2];
        log.info("收到来自 设备号=》{}，topic=》{} 的消息：\n{}", deviceCode, topic, new String(message.getPayload()));
        JSONObject object = JSONObject.parseObject(new String(message.getPayload()));
        DeviceData data = new DeviceData();
        data.setDeviceCode(deviceCode);
        data.setRowData(object);
        data.setReportTime(new Date());
        deviceDataService.save(data);

    }
}
